package com.assets;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.Nullable;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.assets.Adapter.Input_Adapter_item1;
import com.assets.Adapter.Partoculayout_Adapter;
import com.assets.Ip_set.Url;
import com.assets.bean.Input_item1;
import com.assets.bean.Issued_bean;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Allotdetail;
import com.assets.room.entity.Asset;
import com.assets.room.entity.Dept;
import com.assets.room.entity.Place;
import com.assets.room.entity.Worker;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hb.dialog.dialog.LoadingDialog;

import org.angmarch.views.NiceSpinner;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/3/13.
 */

public class Particulars extends Activity {
    private ListView lv;
    private NiceSpinner spinner;
    private String url;//在用资产
    private String url_stock;//待入库
    private String url_unused;//闲置资产
    private ImageView fh;
    private String url_allot, url_shift;
    private Handler handler = new Handler();
    private List<Input_item1> data = new ArrayList<>();
    private List<Input_item1> screenList;
    private List<String> departmentList = new ArrayList<>();
    LoadingDialog loadingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.particulars);
        inview();
        //打包的时候记得改回http
        url_shift = "http://" + Url.IP + "/api/transferQueryById";
        url_allot = "http://" + Url.IP + "/api/allotQueryById";
        url = "http://" + Url.IP + "/api/assetQuery1";
        url_stock = "http://" + Url.IP + "/api/assetQuery0";
        url_unused = "http://" + Url.IP + "/api/assetQuery";
        Intent intent = getIntent();
        if (intent.getStringExtra("state").equals("1")) {

            loadingDialog = new LoadingDialog(this);
            loadingDialog.setMessage("加载中....");//再用资产
            loadingDialog.show();
            load();
        } else if (intent.getStringExtra("state").equals("2")) {
            loadingDialog = new LoadingDialog(this);
            loadingDialog.setMessage("加载中....");
            loadingDialog.show();
            stock_load();
        } else if (intent.getStringExtra("state").equals("3")) {
            loadingDialog = new LoadingDialog(this);
            loadingDialog.setMessage("加载中....");//闲置资产
            loadingDialog.show();
            unused_load();
        } else if (intent.getStringExtra("state").equals("4")) {
            loadingDialog = new LoadingDialog(this);
            loadingDialog.setMessage("加载中....");
            loadingDialog.show();
            shift_load(intent.getStringExtra("repairsId"));
        } else if (intent.getStringExtra("state").equals("5")) {
            loadingDialog = new LoadingDialog(this);
            loadingDialog.setMessage("加载中....");
            loadingDialog.show();
            allot_load(intent.getStringExtra("repairsId"));
        }
    }

    private void shift_load(final String repairsId) {
        spinner.setVisibility(View.GONE);
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient
                    .Builder()
                    .hostnameVerifier(new AllowAllHostnameVerifier())
                    .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                    .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                    .readTimeout(500, TimeUnit.SECONDS)
                    .build();//创建OkHttpClient对象。
            FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
            formBody.add("transferId", repairsId);
            Request request = new Request.Builder()//创建Request 对象。
                    .url(url_shift)
                    .post(formBody.build())//传递请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //回调方法的使用与get异步请求相同
                    Log.i("123123", "error");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String responseData = response.body().string();
                    //回调方法的使用与get异步请求相同
                    LogUtils.d(responseData);
                    handler.post(() -> {
                        /*final List<String> stringList = new ArrayList<>();
                        stringList.add("全部部门");*/
                        Gson gson = new Gson();
                        List<Issued_bean> userList = gson.fromJson(responseData, new TypeToken<List<Issued_bean>>() {
                        }.getType());
                        for (int i = 0; i < userList.size(); i++) {
                            String assetName = userList.get(i).getAssetName();
                            String deptId = userList.get(i).getDeptId();
                            String assetNumber = userList.get(i).getAssetNumber();
                            String userId = userList.get(i).getUserId();
                            String model = userList.get(i).getModel();
                            String type = userList.get(i).getType();
                            String image = "";
                            if (!TextUtils.isEmpty(userList.get(i).getImage())) {
                                image = "http://" + Url.IP + userList.get(i).getImage();
                            }
//                            data.add(new Input_item1(image, assetName, deptId, assetNumber, userId, model, type, ""));
                            departmentList.add(deptId);
                           /* if (!stringList.contains(deptId)) {
                                stringList.add(deptId);
                            }*/
                        }
                      /*  spinner.attachDataSource(stringList);
                        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                screen(stringList.get(position));
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {
                            }
                        });*/
                        Input_Adapter_item1 adapter_item = new Input_Adapter_item1(Particulars.this, R.layout.input_adapter_item, data);
                        lv.setAdapter(adapter_item);
                        loadingDialog.dismiss();
                    });
                }
            });

        }).start();
    }

    private void allot_load(final String repairsId) {
        spinner.setVisibility(View.GONE);
        new Thread(new Runnable() {
            @Override
            public void run() {


                Log.d("这个是详情的地方了", "repairsId: " + repairsId);

                List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
                List<Allotdetail> allotdetails = MyDataBase.init(Particulars.this).allotdetailService().getAllDataById(repairsId);
                for (Allotdetail allotdetail : allotdetails) {
                    Asset asset = MyDataBase.init(Particulars.this).assetDao().queryAllByNumber(allotdetail.getAssetId())/*assetService.getOne(new QueryWrapper<Asset>().eq("asset_number", allotdetail.getAssetId()))*/;
                    if(asset!=null) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        Dept dept = MyDataBase.init(Particulars.this).deptDao().getDeptById(asset.getDeptId())/*deptService.getById(asset.getDeptId())*/;
                        if(dept!=null) {
                            asset.setDeptId(dept.getSimpleName());
                            asset.setUserDept(dept.getSimpleName());
                        }

                        if(asset.getUserId()!=null && !asset.getUserId().equals("")) {
                            Worker worker = MyDataBase.init(Particulars.this).workerService().getWorkerById(asset.getUserId())/*workerService.getById(asset.getUserId())*/;
                            if(worker!=null) {
                                asset.setUserId(worker.getName());
                            }
                        }
                        Place place = MyDataBase.init(Particulars.this).placeDao().getAllById(asset.getPlace())/*placeService.getById(asset.getPlace())*/;
                        if(place!=null) {
                            asset.setType(place.getName());
                        }
				/*if (asset.getImage() != null && !asset.getImage().equals("")) {
					String image = Base64ImageUtil.getImageStr(ConstantUtil.DISK+ConstantUtil.NAME+"/image/" + asset.getImage());
					asset.setImage(image);
				}*/
                        map.put("assetNumber", asset.getAssetNumber());
                        map.put("assetName", asset.getAssetName());
                        map.put("model", asset.getModel());
                        map.put("type", asset.getType());
                        map.put("deptId", asset.getUserDept());
                        map.put("company", asset.getCompany());
                        map.put("division", asset.getDivision());
                        map.put("userId", asset.getUserId());
                        map.put("image", asset.getImage());
                        map.put("jifang",asset.getFinancialCode());
                        map.put("jigui", asset.getAccountant());
                        maps.add(map);
                    }
                }

                Gson gson = new Gson();
                String responseData = gson.toJson(maps);

                List<Issued_bean> userList = gson.fromJson(responseData, new TypeToken<List<Issued_bean>>() {
                                }.getType());
                for (int i = 0; i < userList.size(); i++) {
                    String assetName = userList.get(i).getAssetName();
                    String deptId = userList.get(i).getDeptId();
                    String assetNumber = userList.get(i).getAssetNumber();
                    String userId = userList.get(i).getUserId();
                    String model = userList.get(i).getModel();
                    String type = userList.get(i).getType();
                    String jifang = userList.get(i).getJifang();
                    String jigui = userList.get(i).getJigui();
                    String image = "";
                    if (!TextUtils.isEmpty(userList.get(i).getImage())) {
                        image = "http://" + Url.IP + userList.get(i).getImage();
                    }
//                    data.add(new Input_item1(image, assetName, deptId, assetNumber, userId, model, type, "", jifang, jigui));
                    departmentList.add(deptId);
                                  /*  if (!stringList.contains(deptId)) {
                                        stringList.add(deptId);
                                    }*/
                }
                Input_Adapter_item1 adapter_item = new Input_Adapter_item1(Particulars.this, R.layout.input_adapter_item, data);
                lv.setAdapter(adapter_item);
                loadingDialog.dismiss();



//                OkHttpClient client = new OkHttpClient
//                        .Builder()
//                        .hostnameVerifier(new AllowAllHostnameVerifier())
//                        .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
//                        .connectTimeout(10, TimeUnit.SECONDS)//连接超时
//                        .readTimeout(500, TimeUnit.SECONDS)
//                        .build();//创建OkHttpClient对象。
//                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
//                formBody.add("allotId", repairsId);
//                Request request = new Request.Builder()//创建Request 对象。
//                        .url(url_allot)
//                        .post(formBody.build())//传递请求体
//                        .build();
//                client.newCall(request).enqueue(new Callback() {
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                        //回调方法的使用与get异步请求相同
//                        Log.i("123123", "error");
//                    }
//
//                    @Override
//                    public void onResponse(Call call, Response response) throws IOException {
//                        final String responseData = response.body().string();
//                        //回调方法的使用与get异步请求相同
//                        LogUtils.d(responseData);
//                        handler.post(new Runnable() {
//                            @Override
//                            public void run() {
//                               /* final List<String> stringList = new ArrayList<>();
//                                stringList.add("全部部门");*/
//                                Bitmap bitmap = null;
//                                Gson gson = new Gson();
//                                List<Issued_bean> userList = gson.fromJson(responseData, new TypeToken<List<Issued_bean>>() {
//                                }.getType());
//                                for (int i = 0; i < userList.size(); i++) {
//                                    String assetName = userList.get(i).getAssetName();
//                                    String deptId = userList.get(i).getDeptId();
//                                    String assetNumber = userList.get(i).getAssetNumber();
//                                    String userId = userList.get(i).getUserId();
//                                    String model = userList.get(i).getModel();
//                                    String type = userList.get(i).getType();
//                                    String image = "";
//                                    if (!TextUtils.isEmpty(userList.get(i).getImage())) {
//                                        image = "http://" + Url.IP + userList.get(i).getImage();
//                                    }
//                                    data.add(new Input_item1(image, assetName, deptId, assetNumber, userId, model, type, ""));
//                                    departmentList.add(deptId);
//                                  /*  if (!stringList.contains(deptId)) {
//                                        stringList.add(deptId);
//                                    }*/
//                                }
//                                /*spinner.attachDataSource(stringList);
//                                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                                    @Override
//                                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                                        screen(stringList.get(position));
//                                    }
//
//                                    @Override
//                                    public void onNothingSelected(AdapterView<?> parent) {
//                                    }
//                                });*/
//                                Input_Adapter_item1 adapter_item = new Input_Adapter_item1(Particulars.this, R.layout.input_adapter_item, data);
//                                lv.setAdapter(adapter_item);
//                                loadingDialog.dismiss();
//
//
//                            }
//                        });
//
//                    }
//                });
//
            }
        }).start();
    }

    private void load() {
        //这个是加载再用资产的方法

        Log.d("我离线了", "helllo, 世界你好");

        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();

        List<Asset> assets = MyDataBase.init(Particulars.this).assetDao().queryById1("1");

        for (Asset asset : assets) {

            Map<String, Object> map = new HashMap<String, Object>();
            Worker worker = MyDataBase.init(Particulars.this).workerService().getWorkerById(asset.getUserId());
            if (worker != null) {
                asset.setUserId(worker.getName());
            }

            asset.setPlace(MyDataBase.init(Particulars.this).placeDao().getNameById(asset.getPlace()) == null ? "暂无此人":MyDataBase.init(Particulars.this).placeDao().getNameById(asset.getPlace()));
            map.put("assetNumber", asset.getAssetNumber());
            map.put("assetName", asset.getAssetName());
            map.put("model", asset.getModel());
            map.put("type", asset.getPlace());
            map.put("userDept", asset.getUserDept());
            map.put("userId", asset.getUserId());
            map.put("image", asset.getImage());
            map.put("company", asset.getCompany());
            map.put("jifang",asset.getFinancialCode());
            map.put("jigui", asset.getAccountant());
            maps.add(map);
        }

        showResponse(new Gson().toJson(maps));

    }

    private void unused_load() {

        Log.d("我离线了", "helllo, 世界你好");

        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();

        List<Asset> assets = MyDataBase.init(Particulars.this).assetDao().queryById2("4", "13");

        for (Asset asset : assets) {

            Map<String, Object> map = new HashMap<String, Object>();
            Worker worker = MyDataBase.init(Particulars.this).workerService().getWorkerById(asset.getUserId());
            if (worker != null) {
                asset.setUserId(worker.getName());
            }

            asset.setPlace(MyDataBase.init(Particulars.this).placeDao().getNameById(asset.getPlace()) == null ? "暂无此人":MyDataBase.init(Particulars.this).placeDao().getNameById(asset.getPlace()));
            map.put("assetNumber", asset.getAssetNumber());
            map.put("assetName", asset.getAssetName());
            map.put("model", asset.getModel());
            map.put("type", asset.getPlace());
            map.put("userDept", asset.getUserDept());
            map.put("userId", asset.getUserId());
            map.put("image", asset.getImage());
            map.put("company", asset.getCompany());
            map.put("jifang",asset.getFinancialCode());
            map.put("jigui", asset.getAccountant());
            maps.add(map);
        }

        showResponse(new Gson().toJson(maps));

    }

    private void showResponse_unused(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
               /* final List<String> stringList = new ArrayList<>();
                stringList.add("全部部门");*/
                Bitmap bitmap = null;
                Gson gson = new Gson();
                List<Issued_bean> userList = gson.fromJson(responseData, new TypeToken<List<Issued_bean>>() {
                }.getType());
                for (int i = 0; i < userList.size(); i++) {
                    String assetName = userList.get(i).getAssetName();
                    String deptId = userList.get(i).getDeptId();
                    String company = userList.get(i).getCompany();
                    String assetNumber = userList.get(i).getAssetNumber();
                    String userId = userList.get(i).getUserId();
                    String model = userList.get(i).getModel();
                    String type = userList.get(i).getType();
                    String image = "";
                    if (!TextUtils.isEmpty(userList.get(i).getImage())) {
                        image = "http://" + Url.IP + userList.get(i).getImage();
                    }
//                    data.add(new Input_item1(image, assetName, company, assetNumber, userId, model, type, ""));
                    departmentList.add(deptId);
                   /* if (!stringList.contains(deptId)) {
                        stringList.add(deptId);
                    }*/
                }
           /*     spinner.attachDataSource(stringList);
                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        screen(stringList.get(position));
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                    }
                });*/
                Input_Adapter_item1 adapter_item = new Input_Adapter_item1(Particulars.this, R.layout.input_adapter_item, data);
                lv.setAdapter(adapter_item);
                loadingDialog.dismiss();

            }
        });
    }

    private void stock_load() {
        spinner.setVisibility(View.GONE);
        new Thread() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient
                            .Builder()
                            .hostnameVerifier(new AllowAllHostnameVerifier())
                            .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                            .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                            .readTimeout(500, TimeUnit.SECONDS)
                            .build();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("userId", Since_case.getInstance().getUserId())
                            .build();
                    Request request = new Request.Builder()
                            .url(url_stock)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    LogUtils.d(responseData);
                    showResponse_stock(responseData);//解析

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }

    private void showResponse_stock(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                /*final List<String> stringList = new ArrayList<>();
                stringList.add("全部部门");*/
                Gson gson = new Gson();
                List<Issued_bean> userList = gson.fromJson(responseData, new TypeToken<List<Issued_bean>>() {
                }.getType());
                for (int i = 0; i < userList.size(); i++) {
                    String assetName = userList.get(i).getAssetName();
                    String deptId = userList.get(i).getDeptId();
                    String assetNumber = userList.get(i).getAssetNumber();
                    String userId = userList.get(i).getUserId();
                    String model = userList.get(i).getModel();
                    String type = userList.get(i).getType();
                    String image = "";
                    if (!TextUtils.isEmpty(userList.get(i).getImage())) {
                        image = "http://" + Url.IP + userList.get(i).getImage();
                    }
//                    data.add(new Input_item1(image, assetName, deptId, assetNumber, userId, model, type, ""));
                    departmentList.add(deptId);
                   /* if (!stringList.contains(deptId)) {
                        stringList.add(deptId);
                    }*/
                }
                /*spinner.attachDataSource(stringList);
                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        screen(stringList.get(position));
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                    }
                });*/
                Input_Adapter_item1 adapter_item = new Input_Adapter_item1(Particulars.this, R.layout.input_adapter_item, data);
                lv.setAdapter(adapter_item);
                loadingDialog.dismiss();
            }
        });
    }



    private void showResponse(final String responseData) {
        List<String> stringList = new ArrayList<>();
        stringList.add("全部部门");
        Gson gson = new Gson();
        List<Issued_bean> userList = gson.fromJson(responseData, new TypeToken<List<Issued_bean>>() {
        }.getType());
        for (int i = 0; i < userList.size(); i++) {
            String assetName = userList.get(i).getAssetName();
//            String dept = userList.get(i).getUserDept();
            String dept = userList.get(i).getCompany();
            String jifan = userList.get(i).getJifang();
            String jigui = userList.get(i).getJigui();

            LogUtils.d(dept);

            String assetNumber = userList.get(i).getAssetNumber();
            String userId = "".equals(userList.get(i).getUserId()) ? "暂无使用人" : userList.get(i).getUserId();
            String model = userList.get(i).getModel();
            String type = "".equals(userList.get(i).getType()) ?  "暂无位置" : userList.get(i).getType();
            String image = "";
            String company = userList.get(i).getCompany();

            if (!TextUtils.isEmpty(userList.get(i).getImage())) {
                image = "http://" + Url.IP + userList.get(i).getImage();
            }
//            data.add(new Input_item1(image, assetName, company, assetNumber, userId, model, type, "", jifan, jigui));
            departmentList.add(dept);
            if (!stringList.contains(dept)) {
                stringList.add(dept);
            }
        }
        runOnUiThread(() -> {
            spinner.attachDataSource(stringList);
            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    screen(stringList.get(position));
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
            Partoculayout_Adapter adapter_item = new Partoculayout_Adapter(Particulars.this, R.layout.particulars_item, data);
            lv.setAdapter(adapter_item);
            loadingDialog.dismiss();
        });
    }

    private void screen(String context) {
        if (context.equals("全部部门")) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Partoculayout_Adapter adapter_item = new Partoculayout_Adapter(Particulars.this, R.layout.particulars_item, data);
                    lv.setAdapter(adapter_item);
                }
            });
            return;
        }
        screenList = new ArrayList<>();
        if (departmentList != null) {
            for (int position = 0; position < departmentList.size(); position++) {
                if (departmentList.get(position).equals(context)) {
                    screenList.add(data.get(position));
                }
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Partoculayout_Adapter adapter_item = new Partoculayout_Adapter(Particulars.this, R.layout.particulars_item, screenList);
                    lv.setAdapter(adapter_item);
                }
            });
        }

    }

    private void inview() {
        fh = (ImageView) findViewById(R.id.fh);
        ImageView rfid_set = findViewById(R.id.rfid_set);
        rfid_set.setVisibility(View.GONE);
        fh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        lv = (ListView) findViewById(R.id.particulars_lv);
        spinner = findViewById(R.id.sp_type);
    }


}
